package me.zhenqu.redis.utils;

/**
 * Created by IntelliJ IDEA.
 * User: yibing.tan
 * Date: 11-11-14
 * Time: 下午4:19
 * To change this template use File | Settings | File Templates.
 */
public class CoderFactory {
    // 支持string, number
    public static <T> CacheCoder getCoder(Class<T> clazz) {
        CacheCoder coder;
        if (String.class.equals(clazz)) {
            coder = StringCoder.INST;
        } else if (Number.class.isAssignableFrom(clazz)) {
            coder = NumberCoder.INST;
        } else if (byte[].class.equals(clazz)) {
            coder = ByteArrayCoder.INST;
        } else if (clazz.isArray()) {
            throw new IllegalArgumentException("use getArrayCoder please");
        } else {
            try {
                clazz.newInstance();
            } catch (Exception e) {
                throw new IllegalArgumentException("class must has a empty constructor");
            }
            coder = new ObjectCoder<T>(clazz);
        }

        return coder;
    }

    public static CacheCoder getArrayCoder(Class<?> clazz) {
        return new ArrayCoder(getCoder(clazz));
    }

    public static CacheCoder getCollectionCoder(Class<?> clazz) {
        return new CollectionCoder(getCoder(clazz));
    }
}
